package com.woyou.ui.activity;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import com.baidu.location.BDLocation;
import com.citaq.ideliver.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMSocialService;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Goods;
import com.woyou.bean.Info;
import com.woyou.bean.MyOrderItem;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.OrderDefaultReq;
import com.woyou.bean.rpc.PayResultReq;
import com.woyou.bean.rpc.QueryActUrlReq;
import com.woyou.bean.rpc.QueryActUrlRes;
import com.woyou.bean.rpc.QueryOrderNoReq;
import com.woyou.bean.rpc.QueryOrderNoRes;
import com.woyou.bean.rpc.SendOrderReq;
import com.woyou.bean.rpc.SendOrderRes;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.adapter.ReturnOrderAdapter;
import com.woyou.ui.api.BackBan;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.api.IStrategy;
import com.woyou.ui.api.StrategyHandler;
import com.woyou.ui.component.CountdownTextView;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.Dialog;
import com.woyou.utils.LogUtil;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.ShareUtils;
import com.woyou.utils.eventbus.EventRestConfirm;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

@EActivity(R.layout.layout_orderstatus)
public class OrderStatusActivity extends BaseActivity implements IBackEventStrategy, BackBan {

	public static final String TAG = "OrderStatusActivity";
	double lat;
	double lng;

	@ViewById(R.id.container)
	LinearLayout mContariner;

	// 接通中，确认中，接单中，已确认
	RelativeLayout include_orderstatus_view;
	CountdownTextView fm_orderstatus_time_tv;
	// ImageView fm_orderstatus_tel1;
	private AnimationDrawable animationDrawable;
	ImageView fm_orderstatus_sign2;
	ImageView fm_orderstatus_waimaiji;
	ImageView fm_orderstatus_sound;
	TextView fm_orderstatus_msg;
	TextView fm_orderstatus_point;
	RelativeLayout fm_orderstatus_back;

	// 接单成功
	View include_success_view;
	TextView include_success_info;
	TextView include_success_time, include_success_waittime;
	RelativeLayout include_success_seeorder;
	RelativeLayout include_success_shareorder;

	// 订单被拒
	View include_rejected_view;
	TextView include_rejected_info;
	RelativeLayout include_rejected_changeshop;
	RelativeLayout include_rejected_adjustorder;
	RelativeLayout include_rejected_consult;
	RelativeLayout include_rejected_complaint;
	TextView include_rejected_totle;
	LinearLayout include_rejected_layout_tip;

	// 未接通
	View include_notconnected_view;
	RelativeLayout include_notconnected_tryagain;
	RelativeLayout include_notconnected_back;
	RelativeLayout include_notconnected_refund;

	// 接通但是店家未操作
	View include_notaccept_view;
	RelativeLayout include_notaccept_tryagain;
	RelativeLayout include_notaccept_adjustorder;
	RelativeLayout include_notaccept_consult;
	LinearLayout include_notaccept_tip;
	TextView include_notaccept_totle;

	// 返单
	RelativeLayout include_returnorder_view;
	ListView lv;
	ReturnOrderAdapter returnOrderAdapter;

	StatusHandler mStatusHandler;
	// 倒计时
	Timer countdownTimer = null;
	TimerTask countdownTask = null;
	// 在线支付拒绝订单倒计时
	Timer onlineCountdownTimer = null;
	float startTime;

	int waittime = 0;
	int big = 30;
	int small = 0;
	int waitTime = 0;

	// point 的Timer
	int point = 0;
	Timer pointTimer = null;
	TimerTask pointTimerTask = null;

	/** 支付的类型，默认为货到付款 :0， 1为支付宝支付， 2为微信支付 **/
	private int TYPE = 0;

	Handler handler = new Handler();
	// 发送订单的请求
	private SendOrderReq orderReq = null;
	// 订单号
	private String orderId;
	// 商铺电话号码
	private String mPhone;
	// 活动的url
	private String url;
	// 理由
	private String msg;
	// 返单的商品列表
	private List<Goods> goodsList = new ArrayList<Goods>();

	// 订单返回对象
	private CodeResult<QueryOrderNoRes> state;
	private UserInfo userInfo;

	private Dialog dialog = new Dialog();

	private int currView = 0;

	@Override
	public void onResume() {
		super.onResume();
		userInfo = mUserModel.getUserInfo();
		queryStateHanlder.sendEmptyMessage(QUERY_STATE);
	}

	@Override
	public void onPause() {
		super.onPause();
		if (include_success_waittime != null) {
			include_success_waittime.setVisibility(View.GONE);
			waittime = 0;
		}
	}

	/**
	 * 初始化View
	 */
	@AfterViews
	public void initView() {
		obtainInfo();
		connectingOrder(orderId);
	}

	/**
	 * 接通中
	 */
	public void connectingOrder(String orderid) {
		if (orderid != null) {
			resetView();
			orderId = orderid;
			if (TYPE == 0)
				queryStateHanlder.sendEmptyMessage(QUERY_STATE);
			else {
				queryStateHanlder.sendEmptyMessage(QUERY_PAY_RESULT);
			}
		}
	}

	private static final int QUERY_STATE = 0x001;
	private static final int QUERY_SUCCESE = 0x002;
	private static final int QUERY_PAY_RESULT = 0x003;
	/** 轮询订单状态 */
	@SuppressLint("HandlerLeak")
	private Handler queryStateHanlder = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case QUERY_PAY_RESULT:
				starTime = System.currentTimeMillis();
				PayResultReq payResultReq = new PayResultReq();
				payResultReq.setoId(orderId);
				payResultReq.setPwd(mUserModel.getUserInfo().getPwd());
				payResultReq.setuId(mUserModel.getUserInfo().getuId());
				querPayResult(payResultReq);
				animOnUI(true);
				LogUtil.e(TAG, payResultReq.toString());
				break;
			case QUERY_STATE:
				queryOrderStatus();
				queryStateHanlder.sendEmptyMessageDelayed(QUERY_STATE, 2000);
				break;
			case QUERY_SUCCESE:
				closeAnim();
				closeTimer();
				if (include_success_view == null) {
					include_success_view = View.inflate(mContext, R.layout.include_success, null);
					include_success_info = (TextView) include_success_view.findViewById(R.id.include_success_info);
					include_success_info.setOnClickListener(OrderStatusActivity.this);
					include_success_time = (TextView) include_success_view.findViewById(R.id.include_success_time);
					include_success_waittime = (TextView) include_success_view
							.findViewById(R.id.include_success_waittime);
					include_success_seeorder = (RelativeLayout) include_success_view
							.findViewById(R.id.include_success_seeorder);
					include_success_seeorder.setOnClickListener(OrderStatusActivity.this);
					include_success_shareorder = (RelativeLayout) include_success_view
							.findViewById(R.id.include_success_shareorder);
					include_success_shareorder.setOnClickListener(OrderStatusActivity.this);
				}
				mContariner.removeAllViews();
				mContariner.addView(include_success_view);
				// 跳转到活动页面
				getActUrl();
				break;
			default:
				break;
			}
		}
	};

	@Background
	public void getActUrl() {
		QueryActUrlReq queryActUrlReq = new QueryActUrlReq();
		queryActUrlReq.setoId(orderId);
		queryActUrlReq.setuPhone(mUserModel.getUserInfo().getPhone());
		BDLocation bdLocation = mBaiduLocationService.getLastLocation();
		if (bdLocation != null) {
			lat = bdLocation.getLatitude();
			lng = bdLocation.getLongitude();
		}
		queryActUrlReq.setLat(lat + "");
		queryActUrlReq.setLng(lng + "");
		queryActUrlReq.setCityCode("");
		CodeResult<QueryActUrlRes> result = mOrderModel.queryActByOrder(queryActUrlReq);

		if (result != null && result.getCode() == 1) {
			url = result.getBean().getActiveUrl();
			// 跳转到活动页面
			if (url == null || url != null && url.length() <= 0) {
				runOnUI(new Runnable() {
					@Override
					public void run() {
						include_success_info.setVisibility(View.GONE);
						include_success_info.setText("");
					}
				});
			} else {
				runOnUI(new Runnable() {

					@Override
					public void run() {
						include_success_info.setVisibility(View.VISIBLE);
						include_success_waittime.setVisibility(View.GONE);
						include_success_info.setText("点击获得抽奖机会");
					}

				});
			}
		}
	}

	/**
	 * 跳转到活动详情页面
	 */
	@UiThread
	public void jump2ActivitiesFM() {
		if (url != null && url.length() > 0) {
			// 封装发送的数据
			Info<String> sendBean = new Info<String>(url);
			sendBean.setOrigin(OrderStatusActivity_.class);
			openActivity(ActivitiesActivity_.class, sendBean);
			finish();
		}
	}

	/**
	 * 重置View
	 */
	public void resetView() {
		big = 30;
		small = 0;
		point = 0;

		if (include_orderstatus_view == null) {
			include_orderstatus_view = (RelativeLayout) View.inflate(mContext, R.layout.include_orderstatus, null);
			fm_orderstatus_time_tv = (CountdownTextView) include_orderstatus_view
					.findViewById(R.id.fm_orderstatus_time_tv);
			fm_orderstatus_sound = (ImageView) include_orderstatus_view.findViewById(R.id.fm_orderstatus_sound);
			fm_orderstatus_msg = (TextView) include_orderstatus_view.findViewById(R.id.fm_orderstatus_msg);
			fm_orderstatus_waimaiji = (ImageView) include_orderstatus_view.findViewById(R.id.fm_orderstatus_waimaiji);

			fm_orderstatus_sign2 = (ImageView) include_orderstatus_view.findViewById(R.id.fm_orderstatus_sign2);
			fm_orderstatus_point = (TextView) include_orderstatus_view.findViewById(R.id.fm_orderstatus_point);
			fm_orderstatus_back = (RelativeLayout) include_orderstatus_view.findViewById(R.id.fm_orderstatus_back);
			fm_orderstatus_back.setOnClickListener(this);

		}
		mContariner.removeAllViews();
		mContariner.addView(include_orderstatus_view);
		fm_orderstatus_time_tv.setVisibility(View.INVISIBLE);
		fm_orderstatus_sound.setVisibility(View.INVISIBLE);
		fm_orderstatus_time_tv.setText("");
		fm_orderstatus_msg.setText("接通中");
		fm_orderstatus_waimaiji.setImageResource(R.raw.orderstatus_waimaiji);
	}

	/**
	 * 查询订单状态
	 */
	@Background
	void queryOrderStatus() {
		try {
			QueryOrderNoReq orderNoReq = new QueryOrderNoReq();
			orderNoReq.setOrderNo(orderId);
			state = mOrderModel.queryOrderStatus(orderNoReq);
			handleSate(state);
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				return;
			case CONVERSION:
				return;
			case NETWORK:
				return;
			case UNEXPECTED:
				return;
			}
		}
		LogUtil.e(TAG, "查询订单状态=" + state.getCode());
	}

	private boolean flag = true;// 轮询线程标志位
	private long starTime;// 开始轮询时间
	private long outTime = 90 * 1000;
	private float price;

	/**
	 * TODO 订单支付状态轮询
	 * 
	 * @param payResultReq
	 *            void
	 */
	private void querPayResult(final PayResultReq payResultReq) {
		if (!NetWorkCenter.isNetworkConnected(getBaseContext())) { // 断网
			showToastOnUI("网络异常,请检查您的网络");
			return;
		}
		executeTask(new Runnable() {

			@Override
			public void run() {
				while (flag) {
					try {
						Thread.sleep(1000);

						long currTime = System.currentTimeMillis();
						if (currTime - starTime > outTime) {
							flag = false;
							CodeResult<QueryOrderNoRes> result = new CodeResult<QueryOrderNoRes>();
							result.setCode(3);
							handleSate(result);
							showToastOnUI("订单超时了，请重试或者退款！");
							return;
						}
						state = mOrderModel.v2_3queryPayResult(payResultReq);
						LogUtil.e(TAG, "查询支付状态返回=" + state.getCode());
						if (state.getCode() == 1) {
							LogUtil.i(TAG, state.getCode() + "支付状态为1");
							flag = false;
							queryStateHanlder.sendEmptyMessage(QUERY_STATE);
						} else if (state.getCode() == 0) {
							LogUtil.i(TAG, "等待状态" + "支付状态为0");
							continue;
						} else {
							flag = false;
							Info<String> info = new Info<String>();
							info.setData(orderId);
							info.setOrigin(OrderStatusActivity_.class);
							openActivity(OrderDetailActivity.class, info);
							finish();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	/**
	 * 处理状态
	 * 
	 * @param state
	 */
	@UiThread
	void handleSate(CodeResult<QueryOrderNoRes> state) {
		switch (state.getCode()) {
		case 1:
			LogUtil.i(TAG, "1：新订单");
			mStatusHandler = new StatusHandler(new StateNewOrder());
			mStatusHandler.operate();
			break;
		case 2:
			if (currView != 2) {
				LogUtil.i(TAG, "2推送成功");
				mStatusHandler = new StatusHandler(new StatePushSuccess());
				mStatusHandler.operate();
			}
			break;
		case 3:
			if (currView != 3) {
				LogUtil.i(TAG, "3：未接通");
				mStatusHandler = new StatusHandler(new StateNoResponse());
				mStatusHandler.operate();
				queryStateHanlder.removeMessages(QUERY_STATE);
			}
			break;
		case 4:
			if (currView != 4) {
				LogUtil.i(TAG, "4：接通后未应答");
				mStatusHandler = new StatusHandler(new StateNotAccept());
				mStatusHandler.operate();
			}
			break;
		case 5:
			if (currView != 5) {
				LogUtil.i(TAG, "5 ：拒绝");
				msg = state.getMsg();
				mStatusHandler = new StatusHandler(new StateRefuse());
				mStatusHandler.operate();
				queryStateHanlder.removeMessages(QUERY_STATE);
			}
			break;
		case 6:
			if (currView != 6) {
				LogUtil.i(TAG, "6:返单");
				mStatusHandler = new StatusHandler(new StateOutGoods());
				mStatusHandler.operate();
			}
			break;
		case 7:
			LogUtil.i(TAG, "7：已确认");
			if (currView != 7) {
				mStatusHandler = new StatusHandler(new StateConfirm());
				mStatusHandler.operate();
			}
			break;
		case 8:
			LogUtil.i(TAG, "8： 取消");
			if (currView != 8) {
				mStatusHandler = new StatusHandler(new StateCancel());
				mStatusHandler.operate();
			}
			break;
		case 9:
			LogUtil.i(TAG, "9 ：已送出");
			if (currView != 9) {
				mStatusHandler = new StatusHandler(new StateHasSend());
				mStatusHandler.operate();
			}
			break;
		case 10:
			LogUtil.i(TAG, "10 ：已送达");
			break;
		}
		currView = state.getCode();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void onClick(View view) {
		Intent intent;
		switch (view.getId()) {
		case R.id.include_success_seeorder:
			// 跳转到订单详情
			MyOrderItem orderItem = new MyOrderItem();
			orderItem.setoId(orderId);
			Info<MyOrderItem> info = new Info<MyOrderItem>();
			info.setData(orderItem);
			info.setOrigin(OrderStatusActivity_.class);
			openActivity(OrderDetailActivity.class, info);
			// 清空购物车
			mShoppingCarModel.clearShopppingCar();
			// 重置确认订单页面
			EventBus.getDefault().post(new EventRestConfirm());
			finish();
			break;

		case R.id.fm_orderstatus_back:
			// 隐藏呼叫,等通知
			mShoppingCarModel.clearShopppingCar();
			toShops();
			Info<Class> in = new Info<Class>();
			in.setData(ShopsFragment_.class);
			in.setOrigin(OrderStatusActivity_.class);
			openActivity(HomeActivity_.class, in);
			finish();
			break;

		case R.id.include_success_shareorder:
			// 分享订单
			ShareUtils shareUtils = ShareUtils.getInstance(this);
			UMSocialService mController = shareUtils.getmController();
			shareUtils.setShareOrder(orderId);
			mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ,
					SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA);
			mController.openShare(this, false);
			break;

		case R.id.include_rejected_changeshop:
			// 清理购物车
			mShoppingCarModel.clearShopppingCar();
			// 更换店铺
			toShops();
			// 跳转到店铺列表界面
			Info<Class> inf = new Info<Class>();
			inf.setData(ShopsFragment_.class);
			inf.setOrigin(OrderStatusActivity_.class);
			openActivity(HomeActivity_.class, inf);
			finish();
			break;

		case R.id.include_notaccept_adjustorder:
		case R.id.include_rejected_adjustorder:
		case R.id.include_returnorder_adjustorder:
			// 调整订单
			toShops();
			// 跳转到店铺详情页面
			openActivity(ShopInfoActivity.class, null);
			finish();
			break;

		case R.id.include_notaccept_consult:
		case R.id.include_rejected_consult:
			// 传入服务， parse（）解析号码
			intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhone));
			// 通知activtity处理传入的call服务
			startActivity(intent);
			break;

		case R.id.include_rejected_complaint:
			// 传入服务， parse（）解析号码
			// intent = new Intent(Intent.ACTION_CALL,
			// Uri.parse("tel:4008519517"));
			// 通知activtity处理传入的call服务
			// startActivity(intent);
			// 跳转到商品列表
			// intent = new Intent();
			// intent.setClass(mActivity, ServiceProblemActivity_.class);
			// startActivity(intent);
			openActivity(ServiceProblemActivity_.class, null);
			queryStateHanlder.removeMessages(QUERY_STATE);
			if (onlineCountdownTask != null) {
				onlineCountdownTask.cancel();
				onlineCountdownTask = null;
			}
			if (onlineCountdownTimer != null) {
				onlineCountdownTimer.cancel();
				onlineCountdownTimer = null;
			}
			mShoppingCarModel.clearShopppingCar();
			// 重置确认订单页面
			EventBus.getDefault().post(new EventRestConfirm());
			break;

		case R.id.include_notconnected_tryagain:
			if (TYPE == 0) {
				orderReq.setStamp(System.currentTimeMillis() + "");
				showProgressDialog();
				tryAgain();
			} else {
				showProgressDialog("正在重试，请稍后", false);
				reSendOrder();
			}
			break;
		case R.id.include_notaccept_tryagain:
			orderReq.setStamp(System.currentTimeMillis() + "");
			showProgressDialog();
			tryAgain();
			break;

		case R.id.include_notconnected_back:
			// 跳转到店铺详情页面
			closeTimer();
			// 清空优惠券列表
			mShoppingCarModel.clearCouponList();
			openActivity(ShopInfoActivity.class, null);
			finish();
			break;

		case R.id.include_notconnected_refund: // 退款，返回
			/** 未接通时，放弃并且退款，返回何处？ **/
			showProgressDialog("正在退款中，请稍后", false);
			refund();
			break;

		case R.id.include_success_info:
			jump2ActivitiesFM();
			mShoppingCarModel.clearShopppingCar();
			// 重置确认订单页面
			EventBus.getDefault().post(new EventRestConfirm());
		default:
			break;
		}
	}

	private void refund() {
		if (!NetWorkCenter.isNetworkConnected(getBaseContext())) {
			showToastOnUI("网络异常,请检查您的网络");
			return;
		}
		executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					PayResultReq payResultReq = new PayResultReq();
					payResultReq.setoId(orderId);
					payResultReq.setuId(mUserModel.getUserInfo().getuId());
					payResultReq.setPwd(mUserModel.getUserInfo().getPwd());
					CodeResult result = mOrderModel.refund(payResultReq);
					if (result.getCode() == 1) {
						showToastOnUI("退款成功!");
						Info<String> info = new Info<String>();
						info.setData(orderId);
						info.setOrigin(OrderStatusActivity_.class);
						openActivity(OrderDetailActivity.class, info);
						finish();
					} else {
						showToastOnUI("退款失败，请重新尝试！");
					}

				} catch (Exception e) {
					showToastOnUI("退款失败，请重新尝试！");
					e.printStackTrace();
				} finally {
					dismissProgressDialog();
				}
			}
		});

	}

	// 重新推送订单（仅在线支付支持）
	private void reSendOrder() {
		executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					OrderDefaultReq orderDefaultReq = new OrderDefaultReq();
					orderDefaultReq.setoId(orderId);
					orderDefaultReq.setuId(mUserModel.getUserInfo().getuId());
					orderDefaultReq.setPwd(mUserModel.getUserInfo().getPwd());
					CodeResult result = mOrderModel.onlinePayRetryPushOrder(orderDefaultReq);

					LogUtil.e(TAG, "重新推单参数:oederid  " + orderId + "  uid " + mUserModel.getUserInfo().getuId()
							+ "  pwd " + mUserModel.getUserInfo().getPwd());
					LogUtil.e(TAG, "推单返回结果以及信息：" + result.getCode() + "-----" + result.getMsg());

					if (result.getCode() == 1) {
						runOnUI(new Runnable() {
							public void run() {
								starTime = System.currentTimeMillis();
								resetView();
								queryStateHanlder.sendEmptyMessage(QUERY_STATE);
							}
						});
					} else {
						showToastOnUI("重推订单失败，请重新尝试或退款!");
					}
				} catch (Exception e) {
					e.printStackTrace();
					showToastOnUI("重推订单失败，请重新尝试或退款!");
				} finally {
					dismissProgressDialog();
				}

			}
		});

	}

	@Background
	void tryAgain() {
		try {
			// 如果帐号密码在别处登录,需要重新验证
			userInfo = mUserModel.getUserInfo();
			if (orderReq != null && userInfo != null) {
				orderReq.setPwd(userInfo.getPwd());
				orderReq.setuId(userInfo.getuId());
			}

			final int code;
			final String msg;
			if (TYPE == 0) {
				// 发送订单
				final Result<SendOrderRes> result = mOrderModel.v2_3sendOrder(orderReq);
				orderId = result.getData().getOrderNo();
				code = result.getCode();
				msg = result.getMsg();
			} else {

				OrderDefaultReq orderDefaultReq = new OrderDefaultReq();
				orderDefaultReq.setoId(orderId);
				orderDefaultReq.setPwd(mUserModel.getUserInfo().getPwd());
				orderDefaultReq.setuId(mUserModel.getUserInfo().getuId());
				final CodeResult result = mOrderModel.onlinePayRetryPushOrder(orderDefaultReq);
				code = result.getCode();
				msg = result.getMsg();
			}
			runOnUI(new Runnable() {
				@Override
				public void run() {
					if (1 == code) {
						// Toast.makeText(mContext,"订单编号：" +
						// result.getBean().getOrderNo(), 1).show();
						connectingOrder(orderId);
					} else if (-2 == code) {
						showToast("商品暂缺");
					} else if (-3 == code) {
						dialog.LoginToast(mContext, "您的手机号已在别处登录,请重新登录");
					} else {
						showToast(msg);
					}

				}
			});
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case CONVERSION:

				break;
			case HTTP:

				break;
			case NETWORK:
				break;
			case UNEXPECTED:
				break;
			}
		} finally {
			dismissProgressDialog();
		}
	}

	private void toShops() {
		closeTimer();
		// mShoppingCarModel.clearShopppingCar();
		finish();
	}

	/**
	 * 策略： 对成功状态进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateSuccess implements IStrategy {
		@Override
		public void operate() {
			animationDrawable.stop();
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			// include_success_time.setText("预计" + shopDetail.getAvgDeliver() +
			// "分钟后送出");
			fm_orderstatus_msg.setText("接单成功！");
			mContariner.removeAllViews();
			mContariner.addView(include_success_view);

		}
	}

	/**
	 * 策略： 对失败状态进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateFail implements IStrategy {

		@Override
		public void operate() {
			fm_orderstatus_msg.setText("接单失败！");
			waitTime = 0;
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			initRefuseView();
			mContariner.removeAllViews();
			mContariner.addView(include_rejected_view);
		}

	}

	/**
	 * 策略： 对暂缺(返单)进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateOutGoods implements IStrategy {
		@Override
		public void operate() {
			closeAnim();
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			if (include_returnorder_view == null) {
				include_returnorder_view = (RelativeLayout) View.inflate(mContext, R.layout.include_returnorder, null);
				include_returnorder_view.findViewById(R.id.include_returnorder_adjustorder)
						.setOnClickListener(OrderStatusActivity.this);
			}
			mContariner.removeAllViews();
			mContariner.addView(include_returnorder_view);
			goodsList.clear();
			if (state.getBean() != null && state.getBean().getGoodsList() != null) {
				goodsList.addAll(state.getBean().getGoodsList());
			}
			if (returnOrderAdapter == null) {
				lv = (ListView) include_returnorder_view.findViewById(R.id.include_returnorder_lv);
				returnOrderAdapter = new ReturnOrderAdapter(mContext, goodsList);
				lv.setAdapter(returnOrderAdapter);
			} else {
				returnOrderAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 策略： 对订单未接通进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateNoResponse implements IStrategy {
		@Override
		public void operate() {
			if (animationDrawable != null)
				animationDrawable.stop();
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			if (include_notconnected_view == null) {
				include_notconnected_view = View.inflate(mContext, R.layout.include_notconnected, null);
				include_notconnected_tryagain = (RelativeLayout) include_notconnected_view
						.findViewById(R.id.include_notconnected_tryagain);
				include_notconnected_tryagain.setOnClickListener(OrderStatusActivity.this);
				include_notconnected_back = (RelativeLayout) include_notconnected_view
						.findViewById(R.id.include_notconnected_back);
				include_notconnected_refund = (RelativeLayout) include_notconnected_view
						.findViewById(R.id.include_notconnected_refund);
				include_notconnected_back.setOnClickListener(OrderStatusActivity.this);
				include_notconnected_refund.setOnClickListener(OrderStatusActivity.this);
				if (TYPE == 0) {
					// 货到付款
					include_notconnected_refund.setVisibility(View.GONE);
					include_notconnected_back.setVisibility(View.VISIBLE);
				} else {
					// 在线支付
					include_notconnected_refund.setVisibility(View.VISIBLE);
					include_notconnected_back.setVisibility(View.GONE);
				}
			}
			mContariner.removeAllViews();
			mContariner.addView(include_notconnected_view);
			starTime = System.currentTimeMillis();
			if (TYPE != 0) {
				if (onlineCountdownTimer != null) {
					onlineCountdownTimer.cancel();
					onlineCountdownTimer = null;

					onlineCountdownTask.cancel();
					onlineCountdownTask = null;
				}
				onlineCountdownTask = new TimerTask() {

					@Override
					public void run() {
						float currTime = System.currentTimeMillis();
						if (currTime - starTime > 180000) {
							Info<String> info = new Info<String>();
							info.setData(orderId);
							info.setOrigin(OrderStatusActivity_.class);
							openActivity(OrderDetailActivity.class, info);
							onlineCountdownTimer.cancel();
							finish();
						}
					}
				};

				onlineCountdownTimer = new Timer();
				onlineCountdownTimer.schedule(onlineCountdownTask, 0, 2000);
			}
		}
	}

	/**
	 * 订单接通后未响应
	 * 
	 * @author 荣
	 *
	 */
	class StateNotAccept implements IStrategy {
		@Override
		public void operate() {
			if (animationDrawable != null)
				animationDrawable.stop();
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			if (include_notaccept_view == null) {
				include_notaccept_view = View.inflate(mContext, R.layout.include_notaccept, null);
				include_notaccept_tryagain = (RelativeLayout) include_notaccept_view
						.findViewById(R.id.include_notaccept_tryagain);
				include_notaccept_adjustorder = (RelativeLayout) include_notaccept_view
						.findViewById(R.id.include_notaccept_adjustorder);
				include_notaccept_consult = (RelativeLayout) include_notaccept_view
						.findViewById(R.id.include_notaccept_consult);
				include_notaccept_tip = (LinearLayout) include_notaccept_view
						.findViewById(R.id.include_notaccept_tip_root);
				include_notaccept_totle = (TextView) include_notaccept_view.findViewById(R.id.include_notaccept_totle);
				include_notaccept_tryagain.setOnClickListener(OrderStatusActivity.this);
				include_notaccept_adjustorder.setOnClickListener(OrderStatusActivity.this);
				include_notaccept_consult.setOnClickListener(OrderStatusActivity.this);
				if (TYPE == 0) {
					include_notaccept_totle.setVisibility(View.GONE);
					include_notaccept_tip.setVisibility(View.GONE);
				} else {
					include_notaccept_totle.setVisibility(View.VISIBLE);
					include_notaccept_tip.setVisibility(View.VISIBLE);

					BigDecimal b1 = new BigDecimal(mShoppingCarModel.getTotalCost());
					double f1 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					include_notaccept_totle.setText(f1 + "");
					include_notaccept_tryagain.setVisibility(View.GONE);

				}
			}
			mContariner.removeAllViews();
			mContariner.addView(include_notaccept_view);
			playSuccess(R.raw.error);
		}
	}

	/**
	 * 策略： 对新订单(接通中)进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateNewOrder implements IStrategy {
		@Override
		public void operate() {
			animOnUI(true);
		}
	}

	/**
	 * 策略： 对取消订单进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateCancel implements IStrategy {
		@Override
		public void operate() {
			Toast.makeText(mContext, "订单已取消", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 策略： 对拒绝订单进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateRefuse implements IStrategy {
		@Override
		public void operate() {
			if (animationDrawable != null)
				animationDrawable.stop();
			closeTimer();
			queryStateHanlder.removeMessages(QUERY_STATE);
			initRefuseView();
			mContariner.removeAllViews();
			mContariner.addView(include_rejected_view);
			if (msg != null) {
				include_rejected_info.setText("" + msg);
			}
			playSuccess(R.raw.error);
		}
	}

	/**
	 * 策略： 对已接通进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StatePushSuccess implements IStrategy {
		@Override
		public void operate() {
			if (countdownTimer != null)
				return;
			fm_orderstatus_msg.setText("订单确认中");
			fm_orderstatus_time_tv.setVisibility(View.VISIBLE);
			fm_orderstatus_sound.setVisibility(View.VISIBLE);
			fm_orderstatus_waimaiji.setImageResource(R.raw.orderstatus_waimaiji2);

			countdownTimer = new Timer();
			countdownTask = new TimerTask() {
				@Override
				public void run() {
					runOnUI(new Runnable() {
						@Override
						public void run() {
							if (small == 0) {
								waittime++;
								big = big - 1;
								small = 9;
							}
							if (big == 0) {
								big = 29;
							}
							setCountdownTime(fm_orderstatus_time_tv, big, small);
							small = small - 1;

						}
					});
				}
			};
			countdownTimer.schedule(countdownTask, 0, 100);
			animOnUI(false);
		}
	}

	/**
	 * 设置时间样式
	 * 
	 * @param time_view
	 * @param big
	 * @param small
	 */
	public void setCountdownTime(TextView time_view, int big, int small) {
		fm_orderstatus_time_tv.setText(Html.fromHtml("<big>" + big + "</big><small>." + small + "</small>"));
	}

	/**
	 * 策略： 对已确认(待送出)进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateConfirm implements IStrategy {
		@Override
		public void operate() {
			closeTimer();
			closeAnim();
			mContariner.removeAllViews();
			mContariner.addView(include_orderstatus_view);
			fm_orderstatus_msg.setText("订单已确认!");
			fm_orderstatus_time_tv.setVisibility(View.VISIBLE);
			fm_orderstatus_sound.setVisibility(View.GONE);
			fm_orderstatus_waimaiji.setImageResource(R.raw.orderstatus_waimaiji3);
			queryStateHanlder.removeMessages(QUERY_STATE);
			mShoppingCarModel.clearShopppingCar();
			queryStateHanlder.sendEmptyMessageDelayed(QUERY_SUCCESE, 2000);
			playSuccess(R.raw.success);
		}
	}

	/**
	 * 策略： 对已送出进行处理
	 * 
	 * @author longtao.li
	 * 
	 */
	class StateHasSend implements IStrategy {
		@Override
		public void operate() {
		}
	}

	/**
	 * 锦囊 用于实施策略,处理订单状态
	 * 
	 * @author longtao.li
	 * 
	 */
	class StatusHandler extends StrategyHandler {

		IStrategy strategy;

		public StatusHandler(IStrategy strategy) {
			super(strategy);
			this.strategy = strategy;
		}

		public void operate() {
			strategy.operate();
		}

	}

	// 启动动画
	private void anim() {
		// 获取imageview动画列表
		fm_orderstatus_sign2.setImageResource(R.anim.connecting);
		animationDrawable = (AnimationDrawable) fm_orderstatus_sign2.getDrawable();
		if (!animationDrawable.isRunning())
			animationDrawable.start();
		// point
		fm_orderstatus_point.setText("");

		if (pointTimer != null) {
			pointTimer.cancel();
			pointTimer = null;
		}
		if (pointTimerTask != null) {
			pointTimerTask.cancel();
			pointTimerTask = null;
		}
		pointTimer = new Timer();
		pointTimerTask = new TimerTask() {
			@Override
			public void run() {
				runOnUI(new Runnable() {
					public void run() {
						if (point == 0) {
							fm_orderstatus_point.setText("");
							point = 1;
						} else if (point == 1) {
							fm_orderstatus_point.setText(".");
							point = 2;
						} else if (point == 2) {
							fm_orderstatus_point.setText("..");
							point = 3;
						} else {
							fm_orderstatus_point.setText("...");
							point = 0;
						}
					}
				});
			}
		};
		pointTimer.schedule(pointTimerTask, 0, 1000);
	}

	private void closeAnim() {
		if (animationDrawable != null) {
			animationDrawable.stop();
			animationDrawable = null;
		}
	}

	/** 关闭倒计时timer */
	private void closeTimer() {
		if (countdownTimer != null) {
			countdownTimer.cancel();
			countdownTimer = null;
		}
		if (countdownTask != null) {
			countdownTask.cancel();
			countdownTask = null;
		}
		// 关闭点
		if (pointTimer != null) {
			pointTimer.cancel();
			pointTimer = null;
		}
		if (pointTimerTask != null) {
			pointTimerTask.cancel();
			pointTimerTask = null;
		}

	}

	protected void obtainInfo() {
		if (hasInfo()) {
			Object data = mInfo.getData();
			if (data instanceof Map) {
				Map<String, Object> dataMap = (Map<String, Object>) data;
				TYPE = (Integer) (dataMap.containsKey("type") ? dataMap.get("type") : 0);
				if (TYPE == 0) {
					orderReq = (SendOrderReq) dataMap.get("req");
				}
				orderId = (String) dataMap.get("orderid");
				mPhone = (String) dataMap.get("phone");
				price = (Float) dataMap.get("price");
			}
		}
	}

	@Override
	public boolean backOperate() {
		// 不做任何操作
		return true;
	}

	private void initRefuseView() {
		if (include_rejected_view == null) {
			include_rejected_view = View.inflate(mContext, R.layout.include_rejected, null);
			include_rejected_info = (TextView) include_rejected_view.findViewById(R.id.include_rejected_info);
			include_rejected_changeshop = (RelativeLayout) include_rejected_view
					.findViewById(R.id.include_rejected_changeshop);
			include_rejected_changeshop.setOnClickListener(OrderStatusActivity.this);
			include_rejected_adjustorder = (RelativeLayout) include_rejected_view
					.findViewById(R.id.include_rejected_adjustorder);
			include_rejected_adjustorder.setOnClickListener(OrderStatusActivity.this);
			include_rejected_consult = (RelativeLayout) include_rejected_view
					.findViewById(R.id.include_rejected_consult);
			include_rejected_consult.setOnClickListener(OrderStatusActivity.this);
			include_rejected_complaint = (RelativeLayout) include_rejected_view
					.findViewById(R.id.include_rejected_complaint);
			include_rejected_complaint.setOnClickListener(OrderStatusActivity.this);
			include_rejected_layout_tip = (LinearLayout) include_rejected_view

			.findViewById(R.id.include_rejected_tip_root);
			include_rejected_totle = (TextView) include_rejected_view.findViewById(R.id.include_rejected_totle);
			if (TYPE == 0) {
				include_rejected_layout_tip.setVisibility(View.GONE);
			} else {
				include_rejected_layout_tip.setVisibility(View.VISIBLE);
				include_rejected_totle.setText(ParseUtils.formatPrice(price));
			}
		}
	}

	private MediaPlayer mediaPlayer;

	private void playSuccess(int file) {
		mediaPlayer = createLocalMp3(file);
		// 当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
		// 以便其他应用程序可以使用该资源:
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.release();// 释放音频资源
			}
		});
		try {
			// 在播放音频资源之前，必须调用Prepare方法完成些准备工作
			mediaPlayer.prepare();
			// 开始播放音频
			mediaPlayer.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建本地MP3
	 * 
	 * @return
	 */
	public MediaPlayer createLocalMp3(int file) {
		/**
		 * 创建音频文件的方法：
		 * 1、播放资源目录的文件：MediaPlayer.create(MainActivity.this,R.raw.beatit);//
		 * 播放res/raw 资源目录下的MP3文件 2:播放sdcard卡的文件：mediaPlayer=new MediaPlayer();
		 * mediaPlayer.setDataSource("/sdcard/beatit.mp3");//前提是sdcard卡要先导入音频文件
		 */
		MediaPlayer mp = MediaPlayer.create(mActivity, file);
		mp.stop();
		return mp;
	}

	private void animOnUI(final boolean isNoTime) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				if (isNoTime)
					closeTimer();
				anim();

			}
		});

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		queryStateHanlder.removeMessages(QUERY_STATE);
		if (onlineCountdownTask != null) {
			onlineCountdownTask.cancel();
			onlineCountdownTask = null;
		}
		if (onlineCountdownTimer != null) {
			onlineCountdownTimer.cancel();
			onlineCountdownTimer = null;
		}

	}

	// 在线支付倒计时3分钟的处理
	private TimerTask onlineCountdownTask;

}
